/*
 * Copyright 2011 derek.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.aocore.map;

import com.aocore.AoCoreProperties;
import com.aocore.d2data.AreaLevel;
import com.aocore.d2data.GameDifficulty;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.SocketChannel;

/**
 *
 * @author derek
 */
public class MapClient
{
    static MapFrame mapFrame = new MapFrame();

    static public String getSession(int mapid, GameDifficulty gameDifficulty) throws IOException
    {
        Socket socket = new Socket(AoCoreProperties.MAP_SERVER, AoCoreProperties.MAP_PORT);
        PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
        out.write("GET SESSION " + mapid + " " + gameDifficulty.getId() + "\r\n");
        out.flush();
        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        return in.readLine();
    }

    static public void loadMap(String sessionid, AreaLevel areaLevel) throws IOException
    {
        Socket socket = new Socket(AoCoreProperties.MAP_SERVER, AoCoreProperties.MAP_PORT);
        PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
        out.write("LOAD MAP " + sessionid + " " + areaLevel.getId() + "\r\n");
        out.flush();
    }

    static public Map getMap(String sessionid, AreaLevel areaLevel) throws IOException
    {
        ByteBuffer byteBuffer = ByteBuffer.allocate(20000000);
        byteBuffer.order(ByteOrder.LITTLE_ENDIAN); 
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.connect(new InetSocketAddress(AoCoreProperties.MAP_SERVER, AoCoreProperties.MAP_PORT));
        socketChannel.write(ByteBuffer.wrap(("GET MAP " + sessionid + " " + areaLevel.getId() + "\r\n").getBytes()));

        int read = 0;
        while ((read = socketChannel.read(byteBuffer)) != -1)
        {
            System.out.println("read " + read);
        }
        byteBuffer.flip();

        Map map =  new Map(areaLevel, byteBuffer);
        mapFrame.setMap(map);
        return map;
    }
}
